/**
 * @author banglong
 * @date 2016/9/2.
 */
define(['Layer', 'text!../html/components/report/chooseConditionTemp.html!strip', 'avalon', 'tools', 'getVmConfig',
    'stockSearchApi', 'conditionsUtils'
  ],
  function (layer, htmlTemp, avalon, tools, getVmConfig, api, conditionsUtils) {

    var layeroObj;
    var chooseConditionsFunc;
    var apiConfig = {
      className: '',
      method: ''
    };
    var $searchInput;
    var searchValue;

    var goods; // 所有从服务器获取的查询结果
    var timeFlag = {}; // 用作高级定时器的计时标志

    var chooseConditionVm;
    var getVmOption = function () {
      return {

        $id: 'chooseCondition',
        type: 0,
        conditions: [],
        size: 10, // 大小
        pages: 0, // 页数
        count: 0, // 总数

        chooseIndex: 0,
        searchInput: '',
        columnNames: [],
        columnValueNames: [],
        showTBody: false,

        handleSubmit: function (event) {
          event.preventDefault();
          if (typeof chooseConditionsFunc === 'function' && chooseConditionVm.conditions.length !== 0) {
            chooseConditionsFunc(chooseConditionVm.conditions[chooseConditionVm.chooseIndex]);
            layeroObjHide();
          }
        },

        handleSearch: function () {
          tools.throttle(timeFlag, function () {
            var newGoods = searchGoods(chooseConditionVm.searchInput, goods);
            var page = document.querySelector('#conditionsPage');
            page.innerHTML = '';
            tools.initPage(page, chooseConditionVm.size, chooseConditionVm, chooseConditionVm.conditions, newGoods);
          });
        },

        handleKeydown: function (e) {
          var theEvent = e || window.event;
          var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
          switch (code) {
            case 13:
              return;
              break;
            case 27:
              e.preventDefault();
              layeroObjHide();
              break;
            case 38:
              e.preventDefault();
              if (chooseConditionVm.chooseIndex !== 0) {
                chooseConditionVm.chooseIndex--;
              }
              break;
            case 40:
              e.preventDefault();
              if (chooseConditionVm.chooseIndex < (chooseConditionVm.conditions.length - 1)) {
                chooseConditionVm.chooseIndex++;
              }
              break;
          }
        },

        handleClick: function (index) {
          chooseConditionVm.chooseIndex = index;
        },

        handleDBClick: function (index) {
          if (typeof chooseConditionsFunc === 'function') {
            chooseConditionsFunc(chooseConditionVm.conditions[index]);
          }
          layeroObjHide();
        },

        sureCondition: function () {
          if (typeof chooseConditionsFunc === 'function' && chooseConditionVm.conditions.length !== 0) {
            chooseConditionsFunc(chooseConditionVm.conditions[chooseConditionVm.chooseIndex]);
            layeroObjHide();
          }
        },

        hideDialog: function () {
          layeroObjHide();
        },

        showValue: function (el, key) {
          if (typeof el[key] === "boolean") {
            return el[key] ? '是' : '否';
          } else {
            return el[key];
          }
        },

        showClass: function (el, key) {
          if (typeof el[key] === "boolean") {
            return el[key] ? 'blue' : 'red';
          } else {
            return '';
          }
        }
      };
    };

    function searchGoods(value, goods) {
      chooseConditionVm.chooseIndex = 0;
      var index = value.indexOf('(');
      if (index !== -1) {
        value = value.substr(0, index);
      }
      var substrRegex = new RegExp(value, 'i');
      return goods.filter(function (item) {
        if (substrRegex.test(item['PyCode'])) {
          return true;
        } else return substrRegex.test(item[chooseConditionVm.columnValueNames[0]]);
      });
    }

    function layeroObjHide() {
      layer.close(layeroObj);
    }

    function setApiConfig(className, method) {
      apiConfig.className = className;
      apiConfig.method = method;
    }

    function getLayerTitle(type) {
      var title;
      switch (type) {
        case 0:
          title = '科室账户查询';
          setApiConfig('DeptAccountManager', 'GetDepAccounts');
          break;
        case 1:
          title = '账册查询';
          setApiConfig('GoodsBookManager', 'GetGoodsBooks');
          break;
        case 2:
          title = '大类查询';
          setApiConfig('GoodsBigCatManager', 'GetGoodsBigCat');
          break;
        case 3:
          title = '中类查询';
          setApiConfig('GoodsMidCatManager', 'GetGoodsMidCat');
          break;
        case 4:
          title = '小类查询';
          setApiConfig('GoodsSmallCatManager', 'GetGoodsSmallCat');
          break;
        case 5:
          title = '小类查询';
          setApiConfig('DeptGroupManager', 'GetDeptGroup');
          break;
        case 6:
          title = '大类查询';
          setApiConfig('SysPackageBigCatManager', 'GetPackageBigCats');
          break;
      }
      return title;
    }

    // 初始化 物品信息
    function getInitGoods(apiConfig, param) {

      var loadIndex = layer.load();
      var page = document.querySelector('#conditionsPage');
      page.innerHTML = '';

      api.getChooseConditions({
        className: apiConfig.className,
        method: apiConfig.method,
        condition: JSON.stringify(conditionsUtils.getChooseConditions(param))
      }).then(function (jsonResult) {

        if (jsonResult.issuccess !== 0) {
          return Promise.reject('获取信息失败');
        }
        goods = JSON.parse(jsonResult.result);
        var result = searchGoods(searchValue, goods);

        tools.initPage(page, chooseConditionVm.size, chooseConditionVm, chooseConditionVm.conditions, result);
        layer.close(loadIndex);
        chooseConditionVm.showTBody = true;

      })['catch'](function (ex) {
        layer.close(loadIndex);
        tools.handleError(ex);
      });
    }

    var init = function (param) {

      // 此处防止重写加载的原因是防止出现bug
      if (!document.querySelector('#layui-layer' + layeroObj)) {
        var title = getLayerTitle(param.type);
        layeroObj = tools.createNewOpenWindow(['800px', '560px'], title, htmlTemp);
        // 回调函数可以 做销毁操作
        chooseConditionVm = tools.initAvalonVm(avalon, getVmOption(), '.chooseCondition', function () {
          goods = null;
        });

        chooseConditionVm.type = param.type;
        chooseConditionsFunc = param.chooseConditionsFunc;
        chooseConditionVm.showTBody = false;

        chooseConditionVm.columnNames.splice(0, chooseConditionVm.columnNames.length);
        chooseConditionVm.columnNames.pushArray(getVmConfig.getChooseConditionsColumnNames(param.type)); // 获取表格列名
        chooseConditionVm.columnValueNames.splice(0, chooseConditionVm.columnValueNames.length);
        chooseConditionVm.columnValueNames.pushArray(getVmConfig.getChooseConditionsColumnValueNames(param.type)); // 获取表格列名

        // 设置焦点
        $searchInput = document.querySelector('#searchInputForConditions');
        tools.throttle({}, function () {
          $searchInput.focus();
        });

        searchValue = param.searchValue;
        chooseConditionVm.searchInput = searchValue;
        // 获取物品数据
        getInitGoods(apiConfig, param);
      }
    };

    return {
      init: init
    };
  });